import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import Home from '../views/Layout/Home.vue';
import Login from '../views/Layout/Login.vue';
import roleToRouter from '../utils/roleToRouter';

Vue.use(VueRouter);
// 根据角色加载的路由
const asyncRouterMap = [
  {
    path: '/product',
    name: 'Product',
    meta: { title: '商品', isShow: true, icon: 'appstore' },
    component: Home, // 因为总体框架和home相同 所以可以用home组件
    children: [{
      path: 'add',
      name: 'AddProduct',
      meta: { title: '新增商品', isShow: true, icon: 'plus' },
      component: () => import('../views/page/AddProduct.vue'),
    },
    {
      path: 'edit/:id',
      name: 'EditProduct',
      meta: { title: '编辑商品', isShow: false, icon: 'plus' },
      component: () => import('../views/page/AddProduct.vue'),
    },
    {
      path: 'list',
      name: 'ProductList',
      meta: { title: '商品列表', isShow: true, icon: 'menu' },
      component: () => import('../views/page/ProductList.vue'),
    }, {
      path: 'category',
      name: 'Category',
      meta: { title: '商品分类', isShow: true, icon: 'bars' },
      component: () => import('../views/page/Category.vue'),
    }],
  },
];
const routes = [
  {
    path: '/',
    name: 'Home',
    meta: { title: '首页', isShow: true, icon: 'home' },
    component: Home,
    children: [{
      path: 'index',
      name: 'Index',
      meta: { title: '统计', isShow: true, icon: 'area-chart' },
      component: () => import('../views/page/Index.vue'),
    }],
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录', isShow: false, icon: 'plus' },
    component: Login,
  },

];

const router = new VueRouter({
  routes,
});
let isAdded = false;
// 路由守卫
router.beforeEach((to, from, next) => {
  // 如果访问的路径不是login,则需要权限
  if (to.path !== '/login') {
    if (store.state.userInfo.username && store.state.userInfo.appkey && store.state.userInfo.role) {
      const menuRouter = roleToRouter(store.state.userInfo.role, asyncRouterMap);
      // 把过滤过的路由添加进去
      if (!isAdded) {
        store.dispatch('changRouter', routes.concat(menuRouter)).then(() => {
          router.addRoutes(menuRouter);
          next();
        });
        // 向仓库里存入路由是异步的,所以会造成第一次进入时路由没添加进去的情况,所以使用then的方式
        isAdded = true;
      }

      return next();
    }
    return next('/login');
  }
  return next();
});

export default router;
